package com.liuhengjia.aiknowledgebase.common;

import com.fasterxml.jackson.core.type.TypeReference;
import com.liuhengjia.aiknowledgebase.util.Jsons;

import java.util.ArrayList;
import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.ai.chat.messages.*;
import org.springframework.util.StringUtils;

/**
 * 消息包装器
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MessageWrapper {
    private MessageType type;
    private String content;

    public MessageWrapper(Message message) {
        this.type = message.getMessageType();
        this.content = message.getText();
    }

    /**
     * 根据类型分发转换消息
     *
     * @return org.springframework.ai.chat.messages.Message
     */
    public Message toMessage() {
        return switch (type) {
            case USER -> new UserMessage(content);
            case ASSISTANT -> new AssistantMessage(content);
            case SYSTEM -> new SystemMessage(content);
            case TOOL -> throw new UnsupportedOperationException();
        };
    }

    /**
     * 消息包装器列表转会话 JSON 字符串
     *
     * @param messages 消息包装器列表
     * @return 会话 JSON 字符串
     */
    public static String toConversationStr(List<MessageWrapper> messages) {
        return Jsons.object2Json(messages);
    }

    /**
     * 会话 JSON 字符串转消息包装器列表
     *
     * @param conversationStr 会话 JSON 字符串
     * @return 消息包装器列表
     */
    public static List<MessageWrapper> fromConversationStr(String conversationStr) {
        if (!StringUtils.hasText(conversationStr)) {
            return new ArrayList<>();
        }
        TypeReference<List<MessageWrapper>> typeReference = new TypeReference<>() {
        };
        return Jsons.json2Class(conversationStr, typeReference);
    }
}
